﻿/*
 * 由SharpDevelop创建。
 * 用户： liang
 * 日期: 2015/12/26 星期六
 * 时间: 19:35
 * 
 * 要改变这种模板请点击 工具|选项|代码编写|编辑标准头文件
 */
using System;
using System.IO;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using System.IO.Ports;
using System.Text;
using VCOM.Properties;
using System.Data;



namespace VCOM
{

	/// <summary>
	/// Description of MainForm.
	/// </summary>
	
	public partial class MainForm : Form
	{
		private SerialPort sp = new SerialPort();
		public Timer Timer1 = new Timer();
		//private int rxCount = 0;
		private int[] rxBuffer = new int[1024];
		public delegate void UpdateTextEventHandler(string revText);
		public UpdateTextEventHandler updateText;
		public OpenFileDialog ofd;
		public string binPath;
		public byte[] binBuffer;
		public UInt32 gCntRecv = 0;
		public UInt32 gFlgRecvOK = 0;
		public UInt16 sMsgLen = 0;
		public bool sFlgSendOver = false;
		
		public byte[] sendBuffer;
		
		public MainForm()
		{
			
			InitializeComponent();
			this.sp.DataReceived += new SerialDataReceivedEventHandler(this.serialPort_DataReceived);
			cbxParity.DropDownStyle = ComboBoxStyle.DropDownList;
			cbxDataBits.DropDownStyle = ComboBoxStyle.DropDownList;
			cbxBaudRate.DropDownStyle = ComboBoxStyle.DropDownList;
			cbxComPort.DropDownStyle = ComboBoxStyle.DropDownList;
			cbxStopBits.DropDownStyle = ComboBoxStyle.DropDownList;
			
			
		}
		void MainFormLoad(object sender, EventArgs e)
		{
			foreach(string str in System.IO.Ports.SerialPort.GetPortNames())
			{
				cbxComPort.Items.Add(str);
			}
			
			cbxBaudRate.Items.Add("自定义");
			cbxBaudRate.Items.Add("115200");
			cbxBaudRate.Items.Add("9600");
			cbxBaudRate.Items.Add("4800");
			cbxStopBits.Items.Add("1");
            cbxStopBits.Items.Add("1.5");
            cbxStopBits.Items.Add("2");
            cbxDataBits.Items.Add("8");
            cbxDataBits.Items.Add("7");
            cbxDataBits.Items.Add("6");
            cbxDataBits.Items.Add("5");
            cbxParity.Items.Add("无");
            cbxParity.Items.Add("奇检验");
            cbxParity.Items.Add("偶检验");
            
            sp.WriteTimeout = 3000;
            //sp.ReceivedBytesThreshold = 200;
            
            initAllSerialPortSettings();
			if(cbxComPort.Items.Count == 0)
			{
				MessageBox.Show("没有连接串口");
			}
			else
			{
				initOpenSerialPort();
			}
			
			updateText = new UpdateTextEventHandler(UpdateTextBox);

			
		}
		
		public void openSerialPort()
        {
            try
            {
                sp.Open();
            }
            catch (Exception)
            {
                MessageBox.Show("打开串口失败");
            }
            if(sp.IsOpen)
            {
            	btnOpenCom.Text = "关闭串口";
            }
        }
		
		private void closeSerialPort()
        {
            try
            {
                sp.Close();
            }
            catch
            {
            	MessageBox.Show("关闭串口失败");
            }
            if(!sp.IsOpen)
            {
            	btnOpenCom.Text = "打开串口";
            }
        }
		
		private void initOpenSerialPort()
        {
            if (!sp.IsOpen)
            {
                if (cbxComPort.Items.Count == 0)
                {
                    MessageBox.Show("没有搜索到串口！", "错误提示");
                }
                else
                {
                    SetPortProperty();
                    openSerialPort();
                }
            }
            else
            {
                closeSerialPort();
            }
        }
		
		private void initAllSerialPortSettings()
        {
            if (cbxComPort.Items.Count != 0)
            {
            	Settings.Default.PortName = cbxComPort.Items[0].ToString();
            	cbxComPort.Text = Settings.Default.PortName;
            	
            	if (cbxBaudRate.Items.Contains(Settings.Default.BaudRate))
	            {
	                cbxBaudRate.Text = Settings.Default.BaudRate;
	            }
	            else
	            {
	                cbxBaudRate.Text = "115200";
	            }
	            cbxStopBits.Text = Settings.Default.StopBits;
	            cbxDataBits.Text = Settings.Default.DataBits;
	            cbxParity.Text = Settings.Default.Parity;
            }
            else
            {
               	cbxBaudRate.Text = "115200";
               	cbxStopBits.Text = "1";
	            cbxDataBits.Text = "8";
	            cbxParity.Text = "无";
            }

		}
		
		private void SetPortProperty()
        {
            sp.Encoding = Encoding.GetEncoding("GB18030");
            if (cbxComPort.Text != "")
            {
                sp.PortName = cbxComPort.Text.Trim();
            }
            else
            {
                sp.PortName = "XXXX";
            }
            if (cbxBaudRate.Text.Trim() != "自定义")
            {
                try
                {
                   	sp.BaudRate = Convert.ToInt32(cbxBaudRate.Text.Trim());
                }
                catch (Exception exception)
                {
                    MessageBox.Show(exception.ToString(), "异常");
                }
            }
            
            if(cbxDataBits.Text != "")
            {
            	sp.DataBits = Convert.ToInt16(cbxDataBits.Text.Trim());
            }
            else
            {
            	cbxDataBits.Text = "8";
            	sp.DataBits = Convert.ToInt16(cbxDataBits.Text.Trim());
            }
            
            
            if (cbxStopBits.Text == "1.5")
            {
                sp.StopBits = StopBits.OnePointFive;
            }
            else if (cbxStopBits.Text == "1")
            {
                sp.StopBits = StopBits.One;
            }
            else if (cbxStopBits.Text == "2")
            {
                sp.StopBits = StopBits.Two;
            }
            else
            {
                sp.StopBits = StopBits.One;
                cbxStopBits.Text = "1";
            }
            
            if (cbxParity.Text == "无")
            {
                sp.Parity = Parity.None;
            }
            else if (cbxParity.Text == "奇校验")
            {
                sp.Parity = Parity.Odd;
            }
            else if (cbxParity.Text == "偶校验")
            {
                sp.Parity = Parity.Even;
            }
            else
            {
                sp.Parity = Parity.None;
                cbxParity.Text = "无";
            }

        }
		
		private void saveAllSerialPortSettings()
        {
            Settings.Default.PortName = cbxComPort.Text;
            Settings.Default.BaudRate = cbxBaudRate.Text;
            Settings.Default.StopBits = cbxStopBits.Text;
            Settings.Default.DataBits = cbxDataBits.Text;
            Settings.Default.Parity = cbxParity.Text;

            Settings.Default.Save();
        }
		
		void MainFormFormClosing(object sender, FormClosingEventArgs e)
		{
			saveAllSerialPortSettings();
		}
		
		void CbxComPortSelectedIndexChanged(object sender, EventArgs e)
		{
			if (sp.IsOpen)
            {
                closeSerialPort();
            }
			sp.PortName = cbxComPort.Text.Trim();
		}
		
		void CbxComPortClick(object sender, EventArgs e)
		{
			closeSerialPort();
			cbxComPort.Items.Clear();
			foreach(string str in System.IO.Ports.SerialPort.GetPortNames())
			{
				cbxComPort.Items.Add(str);
			}
		}
		
		void CbxBaudRateSelectedIndexChanged(object sender, EventArgs e)
		{
			if (sp.IsOpen)
            {
                closeSerialPort();
            }
            if (cbxBaudRate.Text.Trim() == "自定义")
            {
                cbxBaudRate.DropDownStyle = ComboBoxStyle.DropDown;
                sp.BaudRate = 0x2580;
            }
            else
            {
                cbxBaudRate.DropDownStyle = ComboBoxStyle.DropDownList;
                sp.BaudRate = Convert.ToInt32(cbxBaudRate.Text.Trim());
            }
		}
		void CbxStopBitsSelectedIndexChanged(object sender, EventArgs e)
		{
			if (sp.IsOpen)
            {
                closeSerialPort();
	        }
			
			if (cbxStopBits.Text == "1.5")
            {
                sp.StopBits = StopBits.OnePointFive;
            }
            else if (cbxStopBits.Text == "1")
            {
                sp.StopBits = StopBits.One;
            }
            else if (cbxStopBits.Text == "2")
            {
                sp.StopBits = StopBits.Two;
            }
            else
            {
                sp.StopBits = StopBits.One;
                cbxStopBits.Text = "1";
            }
		}
		void CbxDataBitsSelectedIndexChanged(object sender, EventArgs e)
		{
			if (sp.IsOpen)
            {
                closeSerialPort();
            }
			sp.DataBits = Convert.ToInt16(cbxDataBits.Text.Trim());
		}
		void CbxParitySelectedIndexChanged(object sender, EventArgs e)
		{
			if (sp.IsOpen)
            {
				closeSerialPort();
            }
			
			if (cbxParity.Text == "无")
            {
                sp.Parity = Parity.None;
            }
            else if (cbxParity.Text == "奇校验")
            {
                sp.Parity = Parity.Odd;
            }
            else if (cbxParity.Text == "偶校验")
            {
                sp.Parity = Parity.Even;
            }
            else
            {
                sp.Parity = Parity.None;
                cbxParity.Text = "无";
            }
		}
		void BtnOpenComClick(object sender, EventArgs e)
		{
			if(btnOpenCom.Text == "打开串口")
			{
				openSerialPort();
			}
			else
			{
				closeSerialPort();
			}
		}
		
		public void UpdateTextBox(string revText)
        {
			revText = Utils.HexToStr(revText);
			//tbxRecvData1.AppendText(revText);
			
			#if true
			/* 301打印 */
			int index = revText.IndexOf("23 23");
			
			if(index < 0)
				return;
			
			/* 获取数据长度 */
			string strNum = revText.Substring(index+22*3,5);
			char[] Num = strNum.ToCharArray();
			byte[] Nump = new byte[Num.Length];
			byte[] Numdes = new byte[Num.Length];
			
			for(int i=0;i<Num.Length;i++)
			{
				Nump[i] = Convert.ToByte(Num[i]);
			}
			Ascii2Byte(Numdes,Nump,(UInt16)((Num.Length)));
			
			int DataLen = Numdes[0]<<8|Numdes[1];
			/*********************/
			
			string str = revText.Substring(index,(DataLen+25)*3);
				
			char[] src = str.ToCharArray();
			byte[] p = new byte[src.Length];
			byte[] des = new byte[src.Length];
			UInt16 offset = 0;
			UInt16 PackNum = 0;
			UInt16 cnt = 0;
			int temp_16 = 0;
			Byte[] VIN = new byte[17];
			
			for(int i=0;i<src.Length;i++)
			{
				p[i] = Convert.ToByte(src[i]);
			}
			Ascii2Byte(des,p,(UInt16)((src.Length)));
			#else //323打印
			
			int index = revText.IndexOf("at%ipsend=");
			
			if(index < 0)
				return;
			
			/* 获取数据长度 */
			string strNum = revText.Substring(index+11+22*2,4);
			char[] Num = strNum.ToCharArray();
			byte[] Nump = new byte[Num.Length];
			byte[] Numdes = new byte[Num.Length];
			
			for(int i=0;i<Num.Length;i++)
			{
				Nump[i] = Convert.ToByte(Num[i]);
			}
			Ascii2ByteNOspace(Numdes,Nump,(UInt16)((Num.Length)));
			
			//获取数据长度
			int DataLen = Numdes[0]<<8|Numdes[1];
			/*********************/
			
			string str = revText.Substring(index+11,(DataLen+25)*2);
				
			char[] src = str.ToCharArray();
			byte[] p = new byte[src.Length];
			byte[] des = new byte[src.Length];
			UInt16 offset = 0;
			UInt16 PackNum = 0;
			UInt16 cnt = 0;
			int temp_16 = 0;
			Byte[] VIN = new byte[17];
			
			for(int i=0;i<src.Length;i++)
			{
				p[i] = Convert.ToByte(src[i]);
			}
			Ascii2ByteNOspace(des,p,(UInt16)((src.Length)));
			
			#endif

			
			
			

			if((des[offset+0] == 0x23)&&(des[offset+1] == 0x23))
			{
				tbxRecvData1.Clear();
				tbxRecvData2.Clear();
				tbxRecvData3.Clear();
				tbxRecvData4.Clear();
				
				gCntRecv++;
				lb_1.Text = "接收计数："+gCntRecv.ToString();
				
				#region /* 帧头解析 */
//				tbxRecvData1.AppendText("帧头:"+des[0]+des[1]+"\r\n");
//				tbxRecvData1.AppendText("命令标识:"+des[2]+"\r\n");
//				tbxRecvData1.AppendText("应答标识:"+des[3]+"\r\n");
//				tbxRecvData1.AppendText("识别码:"+des[4]+"\r\n");
//				tbxRecvData1.AppendText("数据加密方式:"+des[21]+"\r\n");
//				temp_16 = des[22]<<8|des[23];
//				tbxRecvData1.AppendText("数据单元长度:"+temp_16+"\r\n");
				for(int i=0;i<17;i++)
				{
					VIN[i] = des[i+4];
				}
				string vin =  System.Text.Encoding.Default.GetString (VIN);
				tbxRecvData1.AppendText("Vin:"+vin+"\r\n");
				offset += 24;
				#endregion
				
				#region /* 上报时间 */
				tbxRecvData1.AppendText("\r\n----上报时间----\r\n");
				tbxRecvData1.AppendText(des[offset+0]+"-"+des[offset+1]+"-"+des[offset+2]+" "+des[offset+3]+":"+des[offset+4]+":"+des[offset+5] +"\r\n");
				offset += 6;
				#endregion
				
				#region/* 电池电压数据包 */
				tbxRecvData2.AppendText("\r\n---电池电压数据包---\r\n");
				offset += 1;/* 消息类型 */
				
				temp_16 =  des[offset+0]<<8|des[offset+1];
				tbxRecvData2.AppendText("单体蓄电池总数:"+temp_16+"\r\n");
				tbxRecvData2.AppendText("动力蓄电池总包数:"+des[offset+2]+"\r\n");
				PackNum = des[offset+2];
				offset += 3;
				
	
				for(int j=0;j<PackNum;j++)
				{
					tbxRecvData2.AppendText("动力蓄电池包号:"+des[offset+0]+"\r\n");
					tbxRecvData2.AppendText("该包单体蓄电池总数:"+des[offset+1]+"\r\n");
					cnt = des[offset+1];
					offset += 2;
					
					int vol16_1 = 0;
					for(int i=0;i<cnt*2;i+=2)
					{
						vol16_1 = des[offset+0+i]<<8|des[offset+1+i];
						tbxRecvData2.AppendText("单体蓄电池电压["+(i/2+1)+"]:"+(float)vol16_1/1000+"V\r\n");
					}
					offset += (ushort)(cnt*2);
					tbxRecvData1.AppendText("\r\n");
				}
				#endregion
				
				
				
				#region/* 动力蓄电池温度数据 */
				tbxRecvData3.AppendText("\r\n---动力蓄电池温度数据---\r\n");
				offset += 1;/* ID */
				
				temp_16 =  des[offset+0]<<8|des[offset+1];
				tbxRecvData3.AppendText("动力蓄电池温度探针总数:"+temp_16+"\r\n");
				tbxRecvData3.AppendText("动力蓄电池总包数:"+des[offset+2]+"\r\n");
				PackNum = des[offset+2];
				offset += 3;
				
				for(int j=0;j<PackNum;j++)
				{
					tbxRecvData3.AppendText("动力蓄电池包号:"+des[offset+0]+"\r\n");
					tbxRecvData3.AppendText("该包电池温度探针总数:"+des[offset+1]+"\r\n");
					cnt = des[offset+1];
					offset += 2;
					
					for(int i=0;i<cnt;i++)
					{
						tbxRecvData3.AppendText("温度探针值["+(i+1)+"]:"+(des[offset+i]-40).ToString()+"℃\r\n");
					}
					offset += (ushort)cnt;
				}
				#endregion
				
				
				#region/* 整车数据 */
				tbxRecvData1.AppendText("\r\n------整车数据------\r\n");
				offset += 1;/* ID */
				
				temp_16 = des[offset+0]<<8|des[offset+1];
				tbxRecvData1.AppendText("车速:"+(float)temp_16/10+"km/h\r\n");
				offset += 2;
				
				int temp_32 = des[offset+0]<<24|des[offset+1]<<16|des[offset+2]<<8|des[offset+3];
				tbxRecvData1.AppendText("行车里程:"+temp_32/10+"km\r\n");
				offset += 4;
				
				byte temp_8 = des[offset+0];
				if(((temp_8 >> 5) & 0x1) == 0x1)
					tbxRecvData1.AppendText("驱动有效\r\n");
				else
					tbxRecvData1.AppendText("驱动无效\r\n");
				if(((temp_8 >> 4) & 0x1) == 0x1)
					tbxRecvData1.AppendText("制动有效\r\n");
				else
					tbxRecvData1.AppendText("制动无效\r\n");
				switch(temp_8 & 0xf)
				{
					case 0:
						tbxRecvData1.AppendText("档位: 空档\r\n");
						break;
					case 1:
					case 2:
					case 3:
					case 4:
					case 5:
					case 6:
						tbxRecvData1.AppendText("档位: "+(temp_8 & 0xf)+"档\r\n");
						break;
					case 0xe:
						tbxRecvData1.AppendText("档位: 倒档\r\n");
						break;
					case 0xf:
						tbxRecvData1.AppendText("档位: 自动档\r\n");
						break;
					default:
						break;
				}
				offset += 1;
				
				tbxRecvData1.AppendText("加速踏板行程值:"+des[offset+0]+"%\r\n");
				offset += 1;
				
				tbxRecvData1.AppendText("制动踏板行程值:"+des[offset+0]*100+"%\r\n");
				offset += 1;
				
				tbxRecvData1.AppendText("充放电状态:");
				if(des[offset+0] == 0x1)
				{
					tbxRecvData1.AppendText("正在充电\r\n");
				}
				else if(des[offset+0] == 0x2)
				{
					tbxRecvData1.AppendText("放电\r\n");
				}
				else
				{
					tbxRecvData1.AppendText("无效数据\r\n");
				}
				offset += 1;
				
				tbxRecvData1.AppendText("电机控制器温度:"+(des[offset+0]-40).ToString()+"℃\r\n");
				offset += 1;
				
				temp_16 = des[offset+0]<<8|des[offset+1];
				tbxRecvData1.AppendText("电机转速:"+temp_16+"r/min\r\n");
				offset += 2;
				
				tbxRecvData1.AppendText("电机温度:"+(des[offset+0]-40).ToString()+"℃\r\n");
				offset += 1;
				
				temp_16 = des[offset+0]<<8|des[offset+1];
				tbxRecvData1.AppendText("电机电压:"+(float)temp_16/10+"V\r\n");
				offset += 2;
				
				temp_16 = des[offset+0]<<8|des[offset+1];
				tbxRecvData1.AppendText("电机电流:"+((float)(temp_16-10000)/10).ToString()+"A\r\n");
				offset += 2;
				
				tbxRecvData1.AppendText("空调温度:"+des[offset+0]+"\r\n");
				offset += 1;
				
				offset += 7;	/* 预留 */
				#endregion
				
				#region/* 定位数据 */
				tbxRecvData1.AppendText("\r\n-------定位数据-------\r\n");
				offset += 1;/* ID */
				
				byte status = des[offset+0];
				if((status & 0x1) == 0x1)
				{
					tbxRecvData1.AppendText("定位状态: 未定位");
				}
				else
				{
					tbxRecvData1.AppendText("定位状态: 已定位");
				}
				if((status>>1 & 0x1) == 0x1)
				{
					tbxRecvData1.AppendText(" 南纬");
				}
				else
				{
					tbxRecvData1.AppendText(" 北纬");
				}
				if((status>>2 & 0x1) == 0x1)
				{
					tbxRecvData1.AppendText(" 西经\r\n");
				}
				else
				{
					tbxRecvData1.AppendText(" 东经\r\n");
				}
				offset += 1;
				
				int jingdu = des[offset+0]<<24|des[offset+1]<<16|des[offset+2]<<8|des[offset+3];
				tbxRecvData1.AppendText("经度:"+jingdu+"\r\n");
				offset += 4;
				
				int weidu = des[offset+0]<<24|des[offset+1]<<16|des[offset+2]<<8|des[offset+3];
				tbxRecvData1.AppendText("纬度:"+weidu+"\r\n");
				offset += 4;
				
				temp_16 = des[offset+0]<<8|des[offset+1];
				tbxRecvData1.AppendText("速度:"+(float)temp_16/10+"km/h\r\n");
				offset += 2;
				
				temp_16 = des[offset+0]<<8|des[offset+1];
				tbxRecvData1.AppendText("方向:"+temp_16+"\r\n");
				offset += 2;
				
				offset += 4;/* 预留 */
				#endregion
				
				#region/* 极值数据 */
				tbxRecvData4.AppendText("\r\n------极值数据-----\r\n");
				offset += 1;
				
				tbxRecvData4.AppendText("最高电压单体所在包号:"+des[offset+0]+"\r\n");
				tbxRecvData4.AppendText("最高电压单体电池序号:"+des[offset+1]+"\r\n");
				temp_16 = des[offset+2]<<8|des[offset+3];
				tbxRecvData4.AppendText("最高电压单体电压值:"+(float)temp_16/1000+"V\r\n");
				offset += 4;
				
				tbxRecvData4.AppendText("最低电压单体所在包号:"+des[offset+0]+"\r\n");
				tbxRecvData4.AppendText("最低电压单体电池序号:"+des[offset+1]+"\r\n");
				temp_16 = des[offset+2]<<8|des[offset+3];
				tbxRecvData4.AppendText("最低电压单体电压值:"+(float)temp_16/1000+"V\r\n");
				offset += 4;
				
				tbxRecvData4.AppendText("最高温度单体所在包号:"+des[offset+0]+"\r\n");
				tbxRecvData4.AppendText("最高温度探针序号:"+des[offset+1]+"\r\n");
				tbxRecvData4.AppendText("最高温度单体温度值:"+(des[offset+2]-40).ToString()+"℃\r\n");
				offset += 3;
				
				tbxRecvData4.AppendText("最低温度单体所在包号:"+des[offset+0]+"\r\n");
				tbxRecvData4.AppendText("最低温度探针序号:"+des[offset+1]+"\r\n");
				tbxRecvData4.AppendText("最低温度单体温度值:"+(des[offset+2]-40).ToString()+"℃\r\n");
				offset += 3;
				
				temp_16 = des[offset+0]<<8|des[offset+1];
				tbxRecvData4.AppendText("总电压:"+(float)temp_16/10+"V\r\n");
				offset += 2;
				
				temp_16 = des[offset+0]<<8|des[offset+1];
				tbxRecvData4.AppendText("总电流:"+((float)(temp_16-10000)/10).ToString()+"A\r\n");
				offset += 2;
				
				tbxRecvData4.AppendText("SOC:"+des[offset+0]*4/10+"%\r\n");
				offset += 1;
				
				temp_16 = des[offset+0]<<8|des[offset+1];
				tbxRecvData4.AppendText("剩余能量:"+(float)temp_16/10+"KW*h\r\n");
				offset += 2;
				
				temp_16 = des[offset+0]<<8|des[offset+1];
				tbxRecvData4.AppendText("绝缘电阻:"+temp_16+"KΩ\r\n");
				offset += 2;
				
				offset += 5;	/* 预留 */
				#endregion
				
				#region/* 报警数据 */
				tbxRecvData4.AppendText("\r\n--------报警数据--------\r\n");
				offset += 1;
				
				temp_16 = des[offset+0]<<8|des[offset+1];
				if((temp_16>>0 & 0x1) == 0x1)
					tbxRecvData4.AppendText("温度差异报警\r\n");
				if((temp_16>>1 & 0x1) == 0x1)
					tbxRecvData4.AppendText("电池极柱高温报警\r\n");
				if((temp_16>>2 & 0x1) == 0x1)
					tbxRecvData4.AppendText("动力蓄电池包过压报警\r\n");
				if((temp_16>>3 & 0x1) == 0x1)
					tbxRecvData4.AppendText("动力蓄电池包欠压报警\r\n");
				if((temp_16>>4 & 0x1) == 0x1)
					tbxRecvData4.AppendText("SOC低报警\r\n");
				if((temp_16>>5 & 0x1) == 0x1)
					tbxRecvData4.AppendText("单体蓄电池过压报警\r\n");
				if((temp_16>>6 & 0x1) == 0x1)
					tbxRecvData4.AppendText("单体蓄电池欠压报警\r\n");
				if((temp_16>>7 & 0x1) == 0x1)
					tbxRecvData4.AppendText("SOC太低报警\r\n");
				if((temp_16>>8 & 0x1) == 0x1)
					tbxRecvData4.AppendText("SOC太高报警\r\n");
				if((temp_16>>9 & 0x1) == 0x1)
					tbxRecvData4.AppendText("动力蓄电池包不匹配报警\r\n");
				if((temp_16>>10 & 0x1) == 0x1)
					tbxRecvData4.AppendText("动力蓄电池一致性差报警\r\n");
				if((temp_16>>11 & 0x1) == 0x1)
					tbxRecvData4.AppendText("绝缘故障\r\n");
				offset += 2;
				
				temp_16 = des[offset+0];
				tbxRecvData4.AppendText("动力蓄电池其他故障总数:"+temp_16+"\r\n");
				offset += 1;
				for(short i=0;i<temp_16;i++)
					tbxRecvData4.AppendText("动力蓄电池其他故障代码"+i+":"+des[offset+i]+"\r\n");
				offset += (ushort)temp_16;
				
				temp_16 = des[offset+0];
				tbxRecvData4.AppendText("电机故障总数:"+des[offset+0]+"\r\n");
				offset += 1;
				for(short i=0;i<temp_16;i++)
					tbxRecvData4.AppendText("电机故障代码"+i+":"+des[offset+i]+"\r\n");
				offset += (ushort)temp_16;
				
				temp_16 = des[offset+0];
				tbxRecvData4.AppendText("其他故障总数:"+des[offset+0]+"\r\n");
				offset += 1;
				for(short i=0;i<temp_16;i++)
					tbxRecvData4.AppendText("其他故障代码"+i+":"+des[offset+i]+"\r\n");
				offset += (ushort)temp_16;
				
				#endregion
			}


        }


		void serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
		{
			System.Threading.Thread.Sleep(200);
			if (sp.IsOpen)
            {
                try
                {
					int count = 0;
                    string s = string.Empty;
                    byte[] buffer = new byte[sp.BytesToRead];
                    count = sp.Read(buffer, 0, buffer.Length);
                    
                    StringBuilder builder = new StringBuilder();
                    for (int i = 0; i < count; i++)
                    {
                        builder.Append(Convert.ToString(buffer[i], 0x10).ToUpper().PadLeft(2, '0'));
                    }
                    s = builder.ToString();

                    Invoke(updateText, new string[] { s });
                }
                catch
                {
                	
                }
  
            }
		}
		
		

		
		private void sendSerailPortData(string data)
        {
            if (sp.IsOpen)
            {
                try
                {
                    byte[] bytes = Encoding.GetEncoding("GB2312").GetBytes(data);
                    int length = bytes.Length;
                    sp.Write(bytes, 0, length);
                }
                catch (Exception)
                {
                    MessageBox.Show("发送数据时发生错误, 串口将被关闭！", "错误提示");
                    closeSerialPort();
                }
            }
            else
            {
                MessageBox.Show("串口未打开，请先打开串口！", "错误提示");
            }
        }
		
		private void sendSerailPortDataByHex(string str)
        {
            string[] strArray = str.Split(new char[] { ' ' });
            StringBuilder builder = new StringBuilder();
            for (int i = 0; i < strArray.Length; i++)
            {
                builder.Append(strArray[i]);
            }
            str = builder.ToString();
            if ((str.Length % 2) != 0)
            {
                str = str.Insert(str.Length - 1, "0");
            }
            byte[] buffer = new byte[str.Length / 2];
            for (int j = 0; j < (str.Length / 2); j++)
            {
                try
                {
                    buffer[j] = Convert.ToByte(str.Substring(j * 2, 2), 0x10);
                }
                catch
                {
                    MessageBox.Show("包含非16进制字符，发送失败！", "提示");
                    return;
                }
            }
            if (this.sp.IsOpen)
            {
                try
                {
                    this.sp.Write(buffer, 0, buffer.Length);
                }
                catch (Exception)
                {
                    MessageBox.Show("发送数据时发生错误, 串口将被关闭！", "错误提示");
                    closeSerialPort();
                }
            }
            else
            {
                MessageBox.Show("串口未打开，请先打开串口！", "错误提示");
            }
        }

		
		UInt16 CheckSum16(byte[] buf,UInt32 index,UInt32 len)
		{
			UInt32    i=0;
			UInt32 Sum=0;
		    UInt16 CheckSum=0;
		
		    for (i=index;i<(len+index);i++)
			{
				Sum+=buf[i];
			}
			CheckSum = (UInt16)((Sum >>16) + (Sum & 0xffff));
			return CheckSum;
		}
		
		void Byte2Ascii(byte[] des,byte[] src,UInt16 cnt)
		{
		    byte high;
		    byte low;
		    UInt16 i = cnt;
		    for(i=0;i<cnt;i++)
		    {
		    	high = (byte)(src[i] >> 4);
		    	low  = (byte)(src[i] & 0xf);
			    if (high > 9)
			    	high = (byte)(high + 'A' - 0xA);
			    else
			    	high = (byte)(high + '0');
			    des[i*2] = high;
			    
			    if (low > 9)
			    	low = (byte)(low + 'A' - 0xA);
			    else
			    	low = (byte)(low + '0');
			    des[i*2+1] = low;
		    }
		}
		
		void Ascii2Byte(byte[] des,byte[] src,UInt16 cnt)
		{
			UInt32 i = 0;
			UInt32 j = 0;
			byte highData;
			byte lowData;
			while (i < cnt) 
			{
				if(src[i] == ' ')
				{
					i++;
					continue;
				}
				if (src[i] <= '9' && src[i] >= '0')
					highData = (byte)(src[i] - '0');
				else
					highData = (byte)(src[i] - 'A' + 0xa);
				i++;
				if (src[i] <= '9' && src[i] >= '0')
					lowData = (byte)(src[i] - '0');
				else
					lowData = (byte)(src[i] - 'A' + 0xa);
				des[j] = (byte)(lowData + (highData << 4));
				j++;
				i++;
			}
		}
		
		void Ascii2ByteNOspace(byte[] des,byte[] src,UInt16 cnt)
		{
			UInt32 i = 0;
			UInt32 j = 0;
			byte highData;
			byte lowData;
			while (i < cnt) 
			{
				if (src[i] <= '9' && src[i] >= '0')
					highData = (byte)(src[i] - '0');
				else
					highData = (byte)(src[i] - 'A' + 0xa);
				i++;
				if (src[i] <= '9' && src[i] >= '0')
					lowData = (byte)(src[i] - '0');
				else
					lowData = (byte)(src[i] - 'A' + 0xa);
				des[j] = (byte)(lowData + (highData << 4));
				j++;
				i++;
			}
		}




		void Btn_clearClick(object sender, EventArgs e)
		{
			tbxRecvData1.Clear();
			tbxRecvData2.Clear();
			tbxRecvData3.Clear();
			tbxRecvData4.Clear();
		}
		void Btn_startPraseClick(object sender, EventArgs e)
		{
			sendSerailPortData("GSM1\r\n");
		}
		void TbxRecvData4TextChanged(object sender, EventArgs e)
		{
	
		}

		
	}
}
